package com.taomus.mytools.lang.js.mozilla;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JSMethod {
	private static Logger logger = LoggerFactory.getLogger(JSMethod.class);
	private Context cx;
	private String name;
	private Scriptable scope;

	public JSMethod(String name, Context cx, Scriptable scope) {
		this.name = name;
		this.scope = scope;
		this.cx = cx;
	}

	public Object invoke(Object... args) {
		try {
			Context.enter();
			logger.debug("invoke "+name);
			Object obj = scope.get(name, scope);
			if (obj instanceof Function) {
				Function func = (Function) obj;
				Object result = func.call(cx, scope, scope, args);
				return result;
			}
		} catch (Exception ex) {
			logger.error("JS invoke error ",ex);
			Context.exit();
		}
		finally{
			Context.exit();
		}
		return null;
	}

	public Object invoke() {
		return this.invoke(new Object[]{null});
	}
}
